import axios from 'axios'
// import store from '@/store/index.js'
// import qs from 'qs'
import { getSessionItem } from '@/utils/token'
import { ACCESS_TOKEN, USER_INFO } from '@/variables/storageVariables'
/**
 * @description 处理code异常
 * @param {*} code
 * @param {*} msg
 */

const instance = axios.create({
  baseURL: process.env.NODE_ENV === 'development' ? 'http://192.168.0.196:5052/api' : 'http://192.168.0.196:5052/api',
  timeout: 30000
})
// 请求防抖
const debounceTokenCancel = new Map()
instance.interceptors.request.use(
  config => {
    console.log(config, '请求地址')
    const tokenKey = `${config.method}-${config.url}`
    const cancel = debounceTokenCancel.get(tokenKey)
    if (cancel) {
      cancel()
    }

    console.log(getSessionItem(ACCESS_TOKEN), 'token')
    const token = getSessionItem(ACCESS_TOKEN)
    if (token) {
      // config.headers[tokenName] = store.getters['user/token'];
      config.headers.Authorization = 'Bearer ' + token
    }
    /*   if (config.data && config.headers['Content-Type'] === 'application/json;charset=UTF-8') {
      // eslint-disable-next-line no-lone-blocks
      {
        config.data = qs.stringify(config.data)
      }
      // return config
      return new Promise(resolve => {
        const timer = setTimeout(() => {
          clearTimeout(timer)
          resolve(config)
        }, 200)
        debounceTokenCancel.set(tokenKey, () => {
          clearTimeout(timer)
          resolve(new Error('取消请求'))
        })
      })
    } */
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

instance.interceptors.response.use(
  response => {
    return response.data
  },
  error => {
    // 接收到异常响应的处理开始
    if (error && error.response) {
      // 1.公共错误处理
      // 2.根据响应码具体处理
      switch (error.response.status) {
        case 400:
          error.message = '错误请求'
          break
        case 401:
          error.message = '未授权，请重新登录'
          break
        case 403:
          error.message = '拒绝访问'
          break
        case 404:
          error.message = '请求错误,未找到该资源'
          break
        case 405:
          error.message = '请求方法未允许'
          break
        case 408:
          error.message = '请求超时'
          break
        case 500:
          error.message = '服务器端出错'
          break
        case 501:
          error.message = '网络未实现'
          break
        case 502:
          error.message = '网络错误'
          break
        case 503:
          error.message = '服务不可用'
          break
        case 504:
          error.message = '网络超时'
          break
        case 505:
          error.message = 'http版本不支持该请求'
          break
        default:
          error.message = `连接错误${error.response.status}`
          alert(error.message)
      }
    } else {
      // 超时处理
      if (JSON.stringify(error).includes('timeout')) {
        alert('服务器响应超时，请刷新当前页')
      }
      console.log('连接服务器失败')
      /*   console.log(err) */
    }
  }
)

export default instance
